package com.yun.yun;

import static java.lang.Thread.sleep;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import java.io.InputStream;

import cn.mineki.CardReaders.IDCardInfo;
import cn.mineki.CardReaders.IUsbReaderCallback;
import cn.mineki.CardReaders.MKR200UReader;
import cn.mineki.Utils.CertImageUtils;

public class IdReaderHelper {

    private MKR200UReader idReader = null;
    private byte[] byLic = null;//授权信息
    private String LicPath = "mineki";//授权文件存放路径
    private String LicFilename = "license.bin";//授权文件名称
    private CertImageUtils imageUtils;

    public void initCardReader(Context context) {
        imageUtils = new CertImageUtils(context);
        //获取license.bin文件内容
        try {
            //从assets读license.bin文件
            InputStream inputStream = context.getResources().getAssets().open(LicFilename);
            byLic = new byte[inputStream.available()];
            inputStream.read(byLic);
        }catch (Exception exp){
            //从/sdcard/mineki读license.bin文件
            FileUnits units = new FileUnits();
            byLic = units.readSDFile(LicPath, LicFilename);
        }
        if (idReader == null) {
            idReader = MKR200UReader.getInstance(context);
        }
        idReader.InitReader(byLic, new IUsbReaderCallback() {
            @Override
            public void ReaderInitSucc() {
                Log.v("1231231","ReaderInitSucc");
                String[] sRet = new String[1];
                Log.v("1231231","模块号:" + idReader.ReadSAMID(sRet).trim());

                readIDCard();
//                IdcardThread idcardThread = new IdcardThread();
//                idcardThread.start();
//                initReaderSuccess = true;
//                tvSAMID.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        btnReadIDCard.setEnabled(true);
//                        btnReadSAMID.setEnabled(true);
//                        //check_result.setText("读卡器初始化成功");
//                    }
//                },0);
            }

            @Override
            public void ReaderInitError() {
                Log.v("1231231","ReaderInitError");

//                initReaderSuccess = false;
//                tvSAMID.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        releaseCardReader(true);
//                        //check_result.setText("读卡器初始化失败");
//                    }
//                },0);
            }

            @Override
            public void UsbAttach() {
                Log.v("1231231","UsbAttach");

//                tvSAMID.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //initCardReader();
//                        check_result.setText("读卡器插入");
//                    }
//                },0);
            }

            @Override
            public void UsbDeAttach() {
                Log.v("1231231","UsbDeAttach");

//                tvSAMID.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        isStop = true;
//                        isRepReadCardTest = false;
//                        releaseCardReader(true);
//                        front_image.setImageResource(R.drawable.zm);
//                        back_image.setImageResource(R.drawable.fm);
//                        img_photo.setImageBitmap(null);
//                        img_pic.setImageBitmap(null);
//                        tvSAMID.setText("");
//                        check_result.setText("读卡器拔出");
//                    }
//                },0);
            }
        });

    }

    public void releaseCardReader() {
        if (idReader != null) {
            idReader.ReleaseReader();
            idReader = null;
//            initReaderSuccess = false;
        }
    }

//    public void initVar(Context context) {
//
//        imageUtils = new CertImageUtils(context);
//        //获取license.bin文件内容
//        try {
//            //从assets读license.bin文件
//            InputStream inputStream = context.getResources().getAssets().open(LicFilename);
//            byLic = new byte[inputStream.available()];
//            inputStream.read(byLic);
//        }catch (Exception exp){
//            //从/sdcard/mineki读license.bin文件
//            FileUnits units = new FileUnits();
//            byLic = units.readSDFile(LicPath, LicFilename);
//        }
//    }

    static private boolean isStop = false;
    private int nSlot = 1;
    private byte[] arrRes = new byte[200];
    private int[] nLen = new int[1];

    private IDCardInfo idCardInfo;

    //读卡
    private void readIDCard() {
//        sStatus = "";
        String[] sRet = new String[1];

        idCardInfo = null;

//        handler.sendEmptyMessage(6);

        new Thread(new Runnable() {
            @Override
            public void run() {
                int time = 5000;
                long start = System.currentTimeMillis();
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    while (idCardInfo == null) {
                        Log.v("1231231","IdcardThread while");
                        long startTime = System.currentTimeMillis();
                        idCardInfo = idReader.ReadBaseCardInfo2(new String[1]);//idCardInfo = idReader.ReadAllCardInfo(new String[1]);
                        long consumingTime = System.currentTimeMillis() - startTime;

                        if (idCardInfo != null) {
                            Log.v("1231231",idCardInfo.getName());
                            Log.v("1231231",idCardInfo.getCardNum());
//                            handler.sendEmptyMessage(4);
//
//                            float distanceValue = consumingTime/1000f;
//                            DecimalFormat decimalFormat =new DecimalFormat("##0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                            String distanceString = decimalFormat.format(distanceValue) + "s";//format 返回的是字符串
//
//                            sStatus = "读取耗时:" + distanceString + "\n";
//
//                            //指纹信息判断
//                            if(idCardInfo.getFingerInfo() != null)
//                                sStatus += idCardInfo.getCardTypeName() + "识读成功，证件含有指纹信息。\n";
//                            else
//                                sStatus += idCardInfo.getCardTypeName() + "识读成功。\n";

//                            //读卡成功后显示证件照片
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    img_pic.setImageBitmap(null);
//                                    //获取证件照片并显示
//                                    img_photo.setImageBitmap(idCardInfo.getPhoto());
//                                    if (bitmap != null && !bitmap.isRecycled()) {
//                                        bitmap.recycle();
//                                        bitmap = null;
//                                    }
//                                    Bitmap[] images = new Bitmap[2];
//                                    //根据证件类型判断是永居证还是身份证
//                                    if (idCardInfo.getCardTypeCode().equals("I")) {
//                                        //生成永居证证件图片
//                                        FPRCardInfo fprCardInfo = (FPRCardInfo) idCardInfo;
//                                        try {
//                                            if (imageUtils.makeFPRCardImages(fprCardInfo, images)) {
//                                                front_image.setImageBitmap(images[0]);
//                                                back_image.setImageBitmap(images[1]);
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    } else if (idCardInfo.getCardTypeCode().equals("J")) {
//                                        GATCardInfo gatCardInfo = (GATCardInfo) idCardInfo;
//                                        //生成港澳台居住证证件图片
//                                        try {
//                                            if (imageUtils.makeGATCardImages(gatCardInfo, images)) {
//                                                front_image.setImageBitmap(images[0]);
//                                                back_image.setImageBitmap(images[1]);
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    } else {
//                                        //生成身份证证件图片
//                                        try {
//                                            if (imageUtils.makeIDCardImages(idCardInfo, images)) {
//                                                front_image.setImageBitmap(images[0]);
//                                                back_image.setImageBitmap(images[1]);
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                    }
//                                    //显示读卡成功文字
//                                    check_result.setText(sStatus);
//                                    check_result.setTextSize(16f);
//                                }
//                            });
                        } else if (System.currentTimeMillis() - start >= time) {//超时
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    sStatus += "识别超时，请重新操作。";
//                                    check_result.setText(sStatus);
//                                    btnReadIDCard.setEnabled(true);
//                                    btn_icCard.setEnabled(true);
//                                    btn_repReadCard.setEnabled(true);
//                                }
//                            });
                            break;
                        } else {
                            try {
                                sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
//                    Log.e(TAG, e.getMessage());
                }
            }
        }).start();
    }

    class IdcardThread extends Thread {
        @Override
        public void run() {
            super.run();
            Log.v("1231231","IdcardThread run");
            int nRet = -1;
            while (!isStop) {
                Log.v("1231231","IdcardThread while");
                try {
                    sleep(500L);
                } catch (InterruptedException var8) {
                    var8.printStackTrace();
                }
                try {
                    nRet = idReader.ResetCard(nSlot, arrRes, nLen);
                    Log.v("1231231","nSlot = "+ nSlot);
                    Log.v("1231231","nRet = "+ nRet);
                    if (nSlot == 2 && nRet == 0 && arrRes[0] == 0x0f) {//如果是二代证返回0x0f
                        Log.v("1231231","111");
                        //idReader.Halt();
                        idCardInfo = idReader.ReadBaseCardInfo2(new String[1]);
                        Log.v("1231231",idCardInfo.getName());
                        Log.v("1231231",idCardInfo.getCardNum());
                        if (idCardInfo != null) {
//                            sStatus = idCardInfo.getCardTypeName() + "识读成功。\n";
                            //读卡成功后显示证件照片

//                            img_pic.setImageBitmap(null);
//                            //获取证件照片并显示
//                            img_photo.setImageBitmap(idCardInfo.getPhoto());
//                            if (bitmap != null && !bitmap.isRecycled()) {
//                                bitmap.recycle();
//                                bitmap = null;
//                            }
//                            Bitmap[] images = new Bitmap[2];
//                            //根据证件类型判断是永居证还是身份证
//                            if (idCardInfo.getCardTypeCode().equals("I")) {
//                                //生成永居证证件图片
//                                FPRCardInfo fprCardInfo = (FPRCardInfo) idCardInfo;
//                                try {
//                                    if (imageUtils.makeFPRCardImages(fprCardInfo, images)) {
//                                        front_image.setImageBitmap(images[0]);
//                                        back_image.setImageBitmap(images[1]);
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            } else if (idCardInfo.getCardTypeCode().equals("J")) {
//                                GATCardInfo gatCardInfo = (GATCardInfo) idCardInfo;
//                                //生成港澳台居住证证件图片
//                                try {
//                                    if (imageUtils.makeGATCardImages(gatCardInfo, images)) {
//                                        front_image.setImageBitmap(images[0]);
//                                        back_image.setImageBitmap(images[1]);
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            } else {
//                                //生成身份证证件图片
//                                try {
//                                    if (imageUtils.makeIDCardImages(idCardInfo, images)) {
//                                        front_image.setImageBitmap(images[0]);
//                                        back_image.setImageBitmap(images[1]);
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            显示读卡成功文字
//                            check_result.setText(sStatus);
//                            check_result.setTextSize(16f);
                        }
//                        else {
//                            handler.sendEmptyMessage(7);//找到TypeB
//                        }
                        try {
                            sleep(500L);
                        } catch (InterruptedException var8) {
                            var8.printStackTrace();
                        }
                    } else if (nRet == 0 && nSlot == 5) {
                        Log.v("1231231","222");

                        //就医卡-1扇区1块，5字节hex
//                        byte[] arrCmd = DataUtils.hexStringToBytes("32420100ffffffffffff");//("3242010090BD1A9F8C65");//("32420100ffffffffffff")
//                        nRet = idReader.TransApduCommand(nSlot, arrCmd,arrCmd.length,arrRes,nLen);
//                        if(nRet == 0 && nLen[0] == 0) {
//                            arrCmd = DataUtils.hexStringToBytes("324304");
//                            nRet = idReader.TransApduCommand(nSlot, arrCmd, arrCmd.length, arrRes, nLen);
//                            if (nRet != 0 || nLen[0] != 16)
//                                continue;
//                            nLen[0] = 5;//前5个字节卡号
//                            isBeepOne = true;
//                        } else continue;

                        //读者证-0扇区2块，asc字符
//                        byte[] arrCmd = DataUtils.hexStringToBytes("32420000ffffffffffff");//("3242010090BD1A9F8C65");//("32420100ffffffffffff")
//                        nRet = idReader.TransApduCommand(nSlot, arrCmd,arrCmd.length,arrRes,nLen);
//                        if(nRet == 0 && nLen[0] == 0) {
//                            arrCmd = DataUtils.hexStringToBytes("324302");
//                            nRet = idReader.TransApduCommand(nSlot, arrCmd, arrCmd.length, arrRes, nLen);
//                            if (nRet != 0 || nLen[0] != 16)
//                                continue;
//                            //nLen[0] = 5;//前5个字节卡号
//                            isBeepOne = true;
//                        } else continue;
//                        handler.sendEmptyMessage(11);//根据nSlot判断卡类别，1TypeA，2TypeB，3电子标签,4二代证,5,M1卡

//                        handler.sendEmptyMessage(7);//根据nSlot判断卡类别，1TypeA，2TypeB，3电子标签,4二代证,5,M1卡
                        try {
                            sleep(500L);
                        } catch (InterruptedException var8) {
                            var8.printStackTrace();
                        }
                    } else if (nRet == 0 && nSlot == 1 && arrRes[0] == 0x0a) {
                        Log.v("1231231","333");

                        String []sRet = new String[1];
//                        bankCardInfo = idReader.ReadBankCardInfo(sRet);
//                        if(bankCardInfo != null) {
//                            handler.sendEmptyMessage(10);
//                        } else {
//                        bankCardInfo = null;
//                        handler.sendEmptyMessage(7);//根据nSlot判断卡类别，1TypeA，2TypeB，3电子标签,4二代证,5,M1卡
//                        }
                        try {
                            sleep(500L);
                        } catch (InterruptedException var8) {
                            var8.printStackTrace();
                        }
                    } else {
                        Log.v("1231231","444");

                        if(nSlot == 2)  nSlot = 5;
                        else if(nSlot == 5) nSlot = 1;
                        else if(nSlot == 1) nSlot = 2;
//                        handler.sendEmptyMessage(8);
                        try {
                            sleep(300L);
                        } catch (InterruptedException var8) {
                            var8.printStackTrace();
                        }
                    }
                }catch (final Exception exp){
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Writer writer = new StringWriter();
//                            PrintWriter printWriter = new PrintWriter(writer);
//                            exp.printStackTrace(printWriter);
//
//                            Throwable cause = exp.getCause();
//                            while (cause != null) {
//                                cause.printStackTrace(printWriter);
//                                cause = cause.getCause();
//                            }
//                            printWriter.close();
//                            String result = writer.toString();
//
//                            Toast.makeText(MainActivity.this, result , Toast.LENGTH_LONG).show();
//                            exp.printStackTrace();
//                        }
//                    });
//                    isRepReadCardTest = false;
                    isStop = true;
                }
            }

//            idcardThread = null;
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    btnInitReader.setEnabled(true);
//                    btnReadIDCard.setEnabled(true);
//                    btnReadSAMID.setEnabled(true);
//                    btn_icCard.setEnabled(true);
//                    check_result.setText("关闭循环找卡测试！");
//                }
//            });
        }
    }
}
